package com.czy.seed.mvc.home.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.czy.seed.mvc.base.service.impl.BaseServiceImpl;
import com.czy.seed.mvc.home.entity.Commodity;
import com.czy.seed.mvc.home.entity.Merchant;
import com.czy.seed.mvc.home.mapper.MerchantMapper;
import com.czy.seed.mvc.home.service.CommodityService;
import com.czy.seed.mvc.home.service.MenuService;
import com.czy.seed.mvc.home.service.MerchantService;
import com.czy.seed.mvc.sys.entity.SysRole;
import com.czy.seed.mvc.sys.entity.SysUser;
import com.czy.seed.mvc.sys.entity.SysUserRole;
import com.czy.seed.mvc.sys.mapper.SysRoleMapper;
import com.czy.seed.mvc.sys.mapper.SysUserMapper;
import com.czy.seed.mvc.sys.mapper.SysUserRoleMapper;
import com.czy.seed.mvc.util.FilesUpload;
import com.czy.seed.mvc.util.PrincipalUtil;
import com.czy.seed.mvc.util.Res;
import com.czy.seed.mybatis.base.QueryParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MerchantServiceImpl extends BaseServiceImpl<Merchant> implements MerchantService {


    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private DataSourceTransactionManager transactionManager;

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private CommodityService commodityService;

    @Autowired
    private MenuService menuServic;

    public static Logger logger = LoggerFactory.getLogger(MerchantServiceImpl.class);

    /**
     * 添加商家信息
     *
     * @param request
     * @return
     */
    @Override
    @Transactional
    public String insertMerchant(MultipartHttpServletRequest request, String url) {
        String msg = "";
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setName("insertMerchant");
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus transaction = transactionManager.getTransaction(def);
        try {
            //新增用户信息
            SysUser sysUser = new SysUser();
            sysUser.setEmail(request.getParameter("mail"));
            sysUser.setName(request.getParameter("companyName"));
            sysUser.setTelephone(request.getParameter("tel"));
            sysUser.setUsername(request.getParameter("username"));
            sysUser.setXmname(request.getParameter("xmname"));
            sysUser.setAddress(request.getParameter("affiliatedRegional"));
            sysUser.setCreateDt(new Date());
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String encodePassword = passwordEncoder.encode("000000");
            sysUser.setPassword(encodePassword);
            sysUserMapper.insert(sysUser);
            sysUser.setCreateBy(sysUser.getId());
            sysUserMapper.updateByPrimaryKey(sysUser);

            //添加默认角色为商家信息
            SysUserRole userRole = new SysUserRole();
            userRole.setSysUserId(sysUser.getId());
            QueryParams queryParams = new QueryParams(SysRole.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andEqualTo("code", "finalist");
            List<SysRole> sysRoles = sysRoleMapper.selectListByParams(queryParams);
            userRole.setSysRoleId(sysRoles.get(0).getId());
            sysUserRoleMapper.insert(userRole);
        /* 添加商家信息 */
            Merchant mer = new Merchant();
            mer.setUserId(sysUser.getId());
            mer.setInstitutionCode(request.getParameter("institutionCode"));
            mer.setIdCardNo(request.getParameter("idCardNo"));
            mer.setAffiliatedRegional(request.getParameter("affiliatedRegional"));
            mer.setBusinessModel(request.getParameter("businessModel"));
            mer.setCompanyName(request.getParameter("companyName"));
            mer.setMail(request.getParameter("mail"));
            mer.setTel(request.getParameter("tel"));
            mer.setGoodsType(request.getParameter("goodsType"));
            mer.setXmname(request.getParameter("xmname"));
            mer.setOfficeId(Long.parseLong(request.getParameter("officeId")));
            mer.setCreationTime(new Date());
            File file = new File(url + request.getParameter("institutionCode"));
            if (!file.exists()) {
                file.mkdirs();
            }
            String URL = new FilesUpload().Upload("file", file.getCanonicalPath(), request, null);
            mer.setCompanyLogo("../lib/images/" + request.getParameter("institutionCode") + "/" + URL);
            int y = merchantMapper.insert(mer);
            msg = "入驻信息提交成功!";
        } catch (Exception e) {
            msg = "入驻信息提交失败！";
            transactionManager.rollback(transaction);
            logger.error("商家入驻信息失败！:{}", e);
        }
        return msg;
    }
@Override
    public List<Merchant> selectMerchant4CreateBy(long userId) {
        return merchantMapper.selectMerchant4CreateBy(userId);
    }
    @Override
    public Map<String, Object> updateNoCut_impl(HttpServletRequest request) {
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        String object = request.getParameter("data");
        Merchant merchant = JSONObject.parseObject(object, Merchant.class);
        //前台传过来的数据有问题，userID为0 再次保存   外键过不去，所以根据ID查的实体，再次进行操作
        try {
            Merchant merchant_ = merchantService.selectByPrimaryKey(merchant.getId());
            QueryParams queryParams = new QueryParams(Merchant.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            merchant_.setType(1);
            merchant_.setUpdateTime(new Date());
            merchantService.updateSelectiveByPrimaryKey(merchant_);
            //将商家所有商品全部上架
            QueryParams queryParams1 = new QueryParams(Commodity.class);
            QueryParams.Criteria criteria1 = queryParams1.createCriteria();
            criteria1.andEqualTo("businessesId", merchant.getId());
            criteria1.andEqualTo("install", "2");//待审批0下架2待审批1上架
//            criteria1.andCondition("install in (0,2)");
            List<Commodity> commodityList = commodityService.selectListByParams(queryParams1);
            for (Commodity commodity : commodityList) {
                commodity.setInstall(1);
                commodity.setUpdteTime(new Date());
                commodityService.updateByPrimaryKey(commodity);
            }
            //依据商家表中的userid查询到user中是否可用的数据并进行更新
            SysUser sysUser=  sysUserMapper.selectByPrimaryKey(merchant_.getUserId());
            sysUser.setEnabled(true);
            sysUser.setUpdateDt(new Date());
            sysUser.setUpdateBy(PrincipalUtil.getLoginUser().getId());
            sysUserMapper.updateByPrimaryKey(sysUser);
            pageInfo.put("status", "true");
        } catch (Exception e) {
            throw new RuntimeException("审核商家出错。");
        }
        return pageInfo;
    }

}
